/*
 * This file is part of the EasyLogger Library.
 *
 * Copyright (c) 2015, Armink, <armink.ztl@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * 'Software'), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Function: Portable interface for each platform.
 * Created on: 2015-04-28
 */
 
#include <elog.h>

#include <stdio.h>

#define OS_ENABLE

#ifdef  OS_ENABLE

#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"


// 日志互斥信号量，用于同步日志输出，避免多任务环境下的日志混乱
static SemaphoreHandle_t LogMutexSemaphore = NULL;

// 如果定义了异步输出使能，则额外创建一个任务和一个二进制信号量用于异步日志输出
#ifdef ELOG_ASYNC_OUTPUT_ENABLE
    // 异步输出任务句柄
    TaskHandle_t async_thread = NULL;
    // 日志二进制信号量，用于异步输出任务的同步
    static SemaphoreHandle_t LogBinarySemaphore = NULL;
    // 异步输出任务函数，负责在后台异步地输出日志
    static void async_output(void *arg);
#endif


#endif




/**
 * EasyLogger port initialize
 *
 * @return result
 */
ElogErrCode elog_port_init(void) {
    ElogErrCode result = ELOG_NO_ERR;
    /* add your code here */
    
    
#ifdef OS_ENABLE
    LogMutexSemaphore = xSemaphoreCreateMutex();
    if (NULL == LogMutexSemaphore)
    {
        result = ELOG_CREATE_SEM_FAIL;
        return result;
    }
    
    
    #ifdef ELOG_ASYNC_OUTPUT_ENABLE
    const uint16_t stack_depth_words = 1024 / sizeof(StackType_t);
    const UBaseType_t priority = tskIDLE_PRIORITY + 1;
    
    LogBinarySemaphore = xSemaphoreCreateBinary();
    if (NULL == LogBinarySemaphore)
    {
        vSemaphoreDelete(LogMutexSemaphore);
        result = ELOG_CREATE_SEM_FAIL;
        return result;
    }
    
    if (pdPASS != xTaskCreate(
                        async_output,
                        "elog_async",
                        stack_depth_words,
                        NULL,
                        priority,
                        &async_thread))
                        
    {
        vSemaphoreDelete(LogMutexSemaphore);
        vSemaphoreDelete(LogBinarySemaphore);
        result = ELOG_CREATE_TASK_FAIL;
        return result;
    }
    #endif
#endif


    return result;
}

/**
 * EasyLogger port deinitialize
 *
 */
void elog_port_deinit(void) {

    /* add your code here */

}

/**
 * output log port interface
 *
 * @param log output of log
 * @param size log size
 */
void elog_port_output(const char *log, size_t size) {
    
    /* add your code here */
    printf("%.*s", size, log);
}

/**
 * output lock
 */
void elog_port_output_lock(void) {
   
    /* add your code here */
#ifdef OS_ENABLE
    if (xPortIsInsideInterrupt())
    {
        /* 互斥锁不能在中断服务程序中使用 */
        return;
    }
    
    if (NULL != LogMutexSemaphore)
    {
        /* 获取互斥锁 */
        xSemaphoreTake(LogMutexSemaphore, 0xFFFFFFFF);
    }
    
#endif
    
}

/**
 * output unlock
 */
void elog_port_output_unlock(void) {
    
    /* add your code here */
#ifdef OS_ENABLE
    if (xPortIsInsideInterrupt())
    {
        /* 互斥锁不能在中断服务程序中使用 */
        return;
    }
    
    if (NULL != LogMutexSemaphore)
    {
        /* 释放互斥锁 */
        xSemaphoreGive(LogMutexSemaphore);
    }
    
#endif    

}

/**
 * get current time interface
 *
 * @return current time
 */
const char *elog_port_get_time(void) {
    
    /* add your code here */
#ifdef OS_ENABLE
    static char cur_sys_time[16] = {0};
    
    #if (INCLUDE_xTaskGetSchedulerState == 1)
        if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED)
        {
    #endif
            snprintf(cur_sys_time, 16, "tick:%010d", xTaskGetTickCount());
    #if (INCLUDE_xTaskGetSchedulerState == 1)
        }
    #endif
        
    return cur_sys_time;
#else 
    return "00:00:00";
#endif
}

/**
 * get current process name interface
 *
 * @return current process name
 */
const char *elog_port_get_p_info(void) {
    
    /* add your code here */
    return "process";
}

/**
 * get current thread name interface
 *
 * @return current thread name
 */
const char *elog_port_get_t_info(void) {
    
    /* add your code here */
#ifdef OS_ENABLE
    #if (INCLUDE_xTaskGetSchedulerState == 1)
        if ( (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) &&
            !xPortIsInsideInterrupt())
        {
    #endif
            return pcTaskGetName(xTaskGetCurrentTaskHandle());
    #if (INCLUDE_xTaskGetSchedulerState == 1)
        }
    #endif
#endif
    
    
    return "";
}

#ifdef OS_ENABLE
#ifdef ELOG_ASYNC_OUTPUT_ENABLE

void elog_async_output_notice(void)
{
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
    
    if(xPortIsInsideInterrupt())
    {
        xSemaphoreGiveFromISR(LogBinarySemaphore, &xHigherPriorityTaskWoken);
        portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
        return ;
    }

    xSemaphoreGive(LogBinarySemaphore);
}


static void async_output(void *arg)
{
    size_t get_log_size = 0;
    
    #ifdef ELOG_ASYNC_LINE_OUTPUT
    static char poll_get_buf[ELOG_LINE_BUF_SIZE - 4];
    #else
    static char poll_get_buf[ELOG_ASYNC_OUTPUT_BUF_SIZE -4];
    #endif
    
    
    while (true)
    {
        xSemaphoreTake(LogBinarySemaphore, 0xFFFFFFFF);
        while(true)
        {
            #ifdef ELOG_ASYNC_LINE_OUTPUT
            get_log_size = elog_async_get_line_log(poll_get_buf, sizeof(poll_get_buf));
            #else
            get_log_size = elog_async_get_log(poll_get_buf, sizeof(poll_get_buf));
            #endif
            
            if (get_log_size)
            {
                elog_port_output(poll_get_buf, get_log_size);
            }
            else 
            {
                break;
            }
        }
        
    }
}

#endif // ELOG_ASYNC_LINE_OUTPUT
#endif


